package com.fei.BYSJ.controller;

import com.alibaba.fastjson.JSON;
import com.fei.BYSJ.beans.Data;
import com.fei.BYSJ.entity.Order;
import com.fei.BYSJ.entity.User;
import com.fei.BYSJ.service.OrderService;
import com.fei.BYSJ.service.OrdersTagService;
import com.fei.BYSJ.utils.HttpServletRequestUtil;
import com.fei.BYSJ.utils.ResultData;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("order")
public class OrderController {


    @Autowired
    OrderService orderService;
    @Autowired
    OrdersTagService ordersTagService;

    @RequestMapping("/releaseOrder")
    public String
    releaseOrder(HttpSession session, HttpServletRequest request){

       /* String[] tags = request.getParameterValues("tags");*/

        User user = (User) session.getAttribute("user");
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        Order order = new Order();
        order.setUserid(String.valueOf(user.getUserid()));
        order.setOrderbody((String) params.get("orderBody"));
        order.setOrdertitle((String) params.get("orderTitle"));
        order.setPaymoney(new BigDecimal(params.get("payMoney").toString().trim()));
        order.setPaystatus(1);
        order.setFinishstatus(0);
        order.setAccpetstatus(0);
        order.setCommentstatus(0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

        order.setCreatetime(calendar.getTime());
        order.setOrdernum(""
                +sdf.format(calendar.getTime())
                /*+calendar.get(Calendar.YEAR)
                +(calendar.get(Calendar.MONTH)+1)
                +calendar.get(Calendar.DAY_OF_MONTH)
                +calendar.get(Calendar.HOUR_OF_DAY)
                +calendar.get(Calendar.MINUTE)
                +calendar.get(Calendar.SECOND)*/
                +(orderService.countOrderByDay(calendar.getTime())+1)
                );
        int i = orderService.releaseOrder(order);
        /*orderService.findOrderByOrderNum(Integer.parseInt(order.getOrdernum()));
        OrdersTag ordersTag = new OrdersTag();
        ordersTag.setOrderid(Integer.parseInt(order.getOrdernum()));
        for (String tag:tags){
            ordersTag.setTagid(Integer.parseInt(tag));
            ordersTagService.addOrderTag(ordersTag);
        }*/



        if (i==1){
            return "redirect:/order/orderlist";
        }
        return "user/releaseOrder";



    }




    @RequestMapping("/orderlist")
    public ModelAndView orderlist(HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView("user/main");

       // modelAndView.addObject("orderlist",orderService.findAll(user.getUserid()));
        modelAndView.addObject("orderlisttype","accept");
        modelAndView.addObject("orderlist",orderService.findUnAcceptOrder());

        return modelAndView;
    }


    @RequestMapping("/acceptOrderlist")
        public ModelAndView acceptOrderlist(HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView("user/myOrder");

        modelAndView.addObject("orderlisttype","accept");
        modelAndView.addObject("orderlist",orderService.findAcceptOrders(user.getUserid()));
        return modelAndView;
    }
    @RequestMapping("/finishOrderlist")
    public ModelAndView finishOrderlist(HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView("user/myOrder");

        modelAndView.addObject("orderlisttype","finish");
        modelAndView.addObject("orderlist",orderService.findFinishOrders(user.getUserid()));
        return modelAndView;
    }

    @RequestMapping("/releaseOrderlist")
    public ModelAndView releaseOrderlist(HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView("user/myOrder");

        modelAndView.addObject("orderlisttype","release");
        modelAndView.addObject("orderlist",orderService.releaseOrderlists(user.getUserid()));
        return modelAndView;
    }

    @RequestMapping("/orderMessage")
    public ModelAndView orderMessage(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView("order");
        /*modelAndView.addObject("orderlisttype","release");*/
        modelAndView.addObject("order",orderService.findOrderById(Integer.parseInt(params.get("id").toString())));
        return modelAndView;
    }

    @RequestMapping("/personalPerformance")
    public @ResponseBody
    Data
    personalPerformance(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");
        /*ModelAndView modelAndView = new ModelAndView("user/personalPerformance");*/
        int[] totalOrder  =new int[5];


        totalOrder[0]=orderService.findAcceptOrders(user.getUserid()).size()+orderService.findFinishOrders(user.getUserid()).size();
        totalOrder[1]=orderService.findAcceptOrders(user.getUserid()).size();
        totalOrder[2]=orderService.findFinishOrders(user.getUserid()).size();
        totalOrder[3]=orderService.releaseOrderlists(user.getUserid()).size();
        totalOrder[4]=orderService.findAllComplainOrder(user.getUserid()).size();



        /*modelAndView.addObject( "totalOrder",totalOrder);*/
        return ResultData.success("",totalOrder);
    }
    @RequestMapping("/dataPerformance")
    public @ResponseBody
    Data
    dataPerformance(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");
        /*ModelAndView modelAndView = new ModelAndView("user/personalPerformance");*/

        int[] totalOrder  =new int[5];
        List<Order> orders = orderService.totalfindAllOrders(params);
        int ordersNum=orders.size();
        //正在进行工单数
        int acceptOrdersNum = 0;
        int finishOrdersNum = 0;
        int releaseOrdersNum = 0;
        int complainOrdersNum = 0;

        String key = params.get("key").toString();
        int id = 0;
        for (Order o: orders) {
            if(o.getId()!=null){
                if (key==null||key==""){
                    if (o.getUserid()!=null&&o.getAccpetstatus()==0){
                        releaseOrdersNum++;
                    }

                    if (o.getAccpetstatus()==1&&o.getFinishstatus()==0){
                        acceptOrdersNum++;
                    }
                    if (o.getFinishstatus()==1&&o.getCommentstatus()==1){
                        finishOrdersNum++;
                    }
                    if (o.getCommentstatus()==2){
                        complainOrdersNum++;
                    }
                }else {
                    id = Integer.parseInt(params.get("key").toString());

                    if (Integer.parseInt(o.getUserid())==id){
                        releaseOrdersNum++;
                    }
                    if (o.getAcceptuserid()!=null){
                    if (o.getAcceptuserid()==id&&o.getFinishstatus()==0){
                        acceptOrdersNum++;
                    }
                    if (o.getFinishstatus()==1&&o.getCommentstatus()==1&&o.getAcceptuserid()==id){
                        finishOrdersNum++;
                    }
                    if (o.getCommentstatus()==2&&o.getAcceptuserid()==id){
                        finishOrdersNum++;
                    }
                    }
                }
            }
        }





        totalOrder[0]=ordersNum;
        totalOrder[1]=acceptOrdersNum;
        totalOrder[2]=finishOrdersNum;
        totalOrder[3]=releaseOrdersNum;
        totalOrder[4]=complainOrdersNum;



        /*modelAndView.addObject( "totalOrder",totalOrder);*/
        return ResultData.success("",totalOrder);
    }

    @RequestMapping("/acceptOrder")
    public
    String
    acceptOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Order o = orderService.findOrderById(Integer.parseInt(params.get("id").toString()));
        if (o.getAccpetstatus()!=0){
            return "exception";
        }
        o.setAccpetstatus(1);
        o.setAcceptuserid(user.getUserid());
        o.setUpdatetime(calendar.getTime());
             orderService.updateOrder(o);
        return "redirect:/order/orderlist";
    }


    @RequestMapping("/finishOrder")
    public String finishOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());


        Order o = orderService.findOrderById(Integer.parseInt(params.get("id").toString()));
        if (o.getAccpetstatus()==1){
            o.setFinishstatus(1);
            o.setFinishtime(calendar.getTime());

            orderService.updateOrder(o);

            return "redirect:/order/acceptOrderlist";
        }

        return "exception";
    }



    @RequestMapping("/cancelOrder")
    public String cancelOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");



        Order o = orderService.findOrderById(Integer.parseInt(params.get("id").toString()));


        if (o.getAccpetstatus()==0){

            int i = orderService.cancelOrderById(Integer.parseInt(params.get("id").toString()));



            return "redirect:/order/acceptOrderlist";
        }

        return "exception";
    }

    @RequestMapping("/allOrders")
    public @ResponseBody Data allOrders(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");

        System.out.println(">>>>>>>>>>>>>>>>>>>>"+JSON.toJSONString(params));
        int pageNo = Integer.parseInt(params.get("page").toString()) ;
        int pageSize =Integer.parseInt(params.get("limit").toString());
        PageHelper.startPage(pageNo, pageSize);
        if (user.getUsertype()==0) {
        List<Order> lists=  orderService.findAllOrders(params);
            PageInfo<Order> pageInfo = new PageInfo<>(lists);

            return ResultData.success("成功", (int) pageInfo.getTotal(),pageInfo.getList());
        }

        return ResultData.success("",0,"");

    }
    @RequestMapping("/deleteOrder")
    public @ResponseBody Data deleteOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");

        System.out.println(">>>>>>>>>>>>"+JSON.toJSONString(params));
        if (user.getUsertype()==0) {
            int i= orderService.cancelOrderById(Integer.parseInt(params.get("id").toString()));

            return ResultData.success("删除成功", i);
        }

        return ResultData.success("删除失败","");

    }

    @RequestMapping("/updateOrder")
    public @ResponseBody Data updateOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");
        System.out.println(">>>>>>>>>>>>"+JSON.toJSONString(params));
        if (user.getUsertype()==0||(user.getUserid()==Integer.parseInt(params.get("userid").toString()))) {

            Order o = orderService.findOrderById(Integer.parseInt(params.get("id").toString()));
            if (o.getFinishstatus()!=1){
                o.setOrdertitle(params.get("ordertitle").toString());
                o.setOrderbody(params.get("deduction").toString());

                int i= orderService.updateOrder(o);
                return ResultData.success("修改成功", i);
            }else {
                return ResultData.failed("工单已完成不能被修改", "");
            }


        }

        return ResultData.success("修改失败,权限不足","");

    }

    @RequestMapping("/commentOrder")
    public @ResponseBody Data commentOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");

        System.out.println(">>>>>>>>>>>>"+JSON.toJSONString(params));
        Order order =orderService.findOrderById(Integer.parseInt(params.get("id").toString()));
        if (order.getCommentstatus()==0&&order.getFinishstatus()==1){
        if (user.getUsertype()==0||user.getUserid()==Integer.parseInt(order.getUserid())) {
            Order o  = new Order();
            if (params.get("commentstart").toString()!=null){

                o.setCommentstart(Integer.parseInt(params.get("commentstart").toString()));
                o.setCommentstatus(1);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                o.setCommenttime(calendar.getTime());
                o.setId(Integer.parseInt(params.get("id").toString()));

                int i= orderService.updateOrder(o);
                return ResultData.success("评论成功", i);



            }
        }else {
            return ResultData.failed("权限不足", "");
        }



        }

        return ResultData.success("不能重复评论或工单未被完成","");

    }

    @RequestMapping("/complainOrder")
    public @ResponseBody Data complainOrder(HttpSession session, HttpServletRequest request){
        Map<String,Object> params = HttpServletRequestUtil.getRequestParams(request);
        User user = (User) session.getAttribute("user");

        Order order = orderService.findOrderById(Integer.parseInt(params.get("id").toString()));
        System.out.println(">>>>>>>>>>>>"+JSON.toJSONString(params));
        if(order.getFinishstatus()==1&&order.getCommentstatus()==0){
        if (user.getUsertype()==0||user.getUserid()==Integer.parseInt(params.get("userid").toString()) ) {
            Order o  = new Order();
                o.setId(Integer.parseInt(params.get("id").toString()));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            o.setCommenttime(calendar.getTime());

                o.setCommentstatus(2);
                int i= orderService.updateOrder(o);
                return ResultData.success("投诉成功", i);


        }
        }

        return ResultData.success("投诉失败，工单未被完成或已投诉","");

    }


}
